﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Windows.Media;
using XWord.WPF.ApplicationFramework.Threads;
using System.Speech.Synthesis;

namespace XWord.WPF.ApplicationFramework
{
    public interface IWord
    {
        string WordName { get; set; }
    }

    public interface IReadWordEngine : IWord
    {
        void Read();
    }

    public class TTSReadWordEngine : IReadWordEngine
    {

        public void Read()
        {
            synthesizer.SelectVoice(Config.TTSConfig.VoiceName);
            synthesizer.Rate = Config.TTSConfig.Rate;
            synthesizer.Volume = Config.TTSConfig.Volume;
            synthesizer.Speak(WordName);
        }

        public XWordAppConfig Config
        {
            get
            {
                return XWordAppConfig.Current;
            }
        }

        private readonly SpeechSynthesizer synthesizer = new SpeechSynthesizer();

        public string WordName { get; set; }
    }

    public class DefaultReadWordEngine : IReadWordEngine
    {
        public void Read()
        {
            if (!Directory.Exists("Resources"))
            {
                Directory.CreateDirectory("Resources");
            }
            MediaPlayer player = new MediaPlayer();
           // player.Volume = 1;
            player.MediaOpened += delegate
            {
                UIThread.BeginInvoke(() =>
                {
                    player.Play();
                });
            };
            player.MediaFailed += delegate
            {
                var wordAudio = new DictWordAudio() { WordName = WordName };
                wordAudio.DownLoad();
                if (wordAudio.IsCompleted)
                    Read();
            };
            player.Open(new Uri(string.Format("Resources\\{0}.mp3", WordName), System.UriKind.Relative));
            
        }

        public static void UseTTSReadWord(string name)
        {
            var readWordEngine = new TTSReadWordEngine() { WordName = name };
            readWordEngine.Read();
        }

        public static void UseDefaultReadWord(string name)
        {
            var readWordEngine = new DefaultReadWordEngine() { WordName = name };
            readWordEngine.Read();
        }
        public string WordName { get; set; }
    }

    public interface IWordAudio : IWord
    {
        string SearchUrl { get; }

        void DownLoad();

        bool IsCompleted { get; }
    }

    public class DictWordAudio : IWordAudio
    {
        public string SearchUrl
        {
            get { return "http://dict.cn/ws.php?utf8=true&q={0}"; }
        }

        public string WordName { get; set; }

        public void DownLoad()
        {
            WebRequest request = WebRequest.Create(string.Format(SearchUrl, WordName));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            if (!responseFromServer.Contains("Not Found"))
            {
                XmlDocument doc = new XmlDocument();
                doc.InnerXml = responseFromServer;
                var audionode = doc.DocumentElement.SelectNodes("descendant::audio");
                if (audionode.Count > 0)
                {
                    Downloadfile(audionode[0].InnerText, AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + WordName + ".mp3");
                    _isCompleted = true;
                
                }
            }
        }

        /// <summary>
        /// 下载该URL的资源到本地
        /// </summary>
        /// <param name="URL">要下载的资源的地址</param>
        /// <param name="savePath">本地要保存的路径</param>
        public static void Downloadfile(string URL, string savePath)
        {
            WebClient client = new WebClient();
            int n = URL.LastIndexOf('/');
            string URLAddress = URL.Substring(0, n);  //取得网址
            string fileName = URL.Substring(n + 1, URL.Length - n - 1);  //取得文件名
            //string Dir =Htppc Server.MapPath("./");  //下载文件存放路径

            string Path = savePath + '\\' + fileName; //下载文件存放完整路径
            try
            {
                client.DownloadFile(URL, savePath);
            }
            catch (Exception)
            {

                // throw;
            }

        }

        private bool _isCompleted;
        public bool IsCompleted
        {
            get { return _isCompleted; }
        }

    }
}
